package com.madi.company.ui.main.adapter;

import android.animation.Animator;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.aspsine.irecyclerview.animation.AlphaInAnimation;
import com.aspsine.irecyclerview.animation.BaseAnimation;
import com.jaydenxiao.common.commonutils.ToastUitl;
import com.madi.company.R;
import com.madi.company.bean.JobTypeEntity;
import com.madi.company.presenter.JobTypePresenter;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 职位列表 adapter
 * Created by 丁宁
 * on 2016/12/19.
 */

public class JobTypeAdapter extends RecyclerView.Adapter<JobTypeAdapter.MyViewHolder> implements StickyRecyclerHeadersAdapter {
    //动画
    private int mLastPosition = -1;
    private boolean mOpenAnimationEnable = true;
    private Interpolator mInterpolator = new LinearInterpolator();
    private int mDuration = 300;
    private BaseAnimation mSelectAnimation = new AlphaInAnimation();
    private List<JobTypeEntity> mData;
    private List<JobTypeEntity> mParentData;
    private List<JobTypeEntity> mChildData;
    private Context mContext;
    private Map<String, Integer> map = new HashMap<>();
    private JobTypePresenter mPresenter;

    public JobTypeAdapter(Context context, List<JobTypeEntity> jobTypeEntities, List<JobTypeEntity> datas, List<JobTypeEntity> data, JobTypePresenter presenter, Map<String, Integer> map) {
        this.mContext = context;
        this.mData = jobTypeEntities;
        this.mParentData = datas;
        this.mChildData = data;
        this.mPresenter = presenter;
        if (map != null) {
            this.map = map;
        }
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
        final JobTypeEntity entity = mData.get(position);
        holder.mTitle.setText(mData.get(position).getJobTypeName());
        final List<JobTypeEntity> child = new ArrayList<>();
        // 分组三级菜单的数据 child
        for (JobTypeEntity model : mChildData) {
            if (entity.getId() == model.getParentId()) {
                child.add(model);
            }
        }

        // 初始化二级是否展开的状态
        if (entity.getIsChecked()) {
            holder.statusImg.setBackgroundResource(R.mipmap.arrow_up);
            holder.mListView.setVisibility(View.VISIBLE);
        } else {
            holder.statusImg.setBackgroundResource(R.mipmap.arrow_down);
            holder.mListView.setVisibility(View.GONE);
        }
        // 二级菜单点击事件
        holder.mLinear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (entity.getIsChecked()) {
                    entity.setIsChecked(false);
                    holder.statusImg.setBackgroundResource(R.mipmap.arrow_down);
                    holder.mListView.setVisibility(View.GONE);
                } else {
                    holder.mListView.setAdapter(new MyAdapter(child));
                    setListViewHeightBasedOnChildren(holder.mListView);
                    entity.setIsChecked(true);
                    holder.statusImg.setBackgroundResource(R.mipmap.arrow_up);
                    holder.mListView.setVisibility(View.VISIBLE);
                }
            }
        });
        // 三级条目点击事件
        holder.mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CheckBox childChecked = (CheckBox) view.findViewById(R.id.title_check);
                final JobTypeEntity entity = child.get(position);
                if (entity.getIsChecked()) {
                    childChecked.setChecked(false);
                    entity.setIsChecked(false);
                    map.remove(entity.getJobTypeName());
                } else {
                    if (map.size() < 5) {
                        childChecked.setChecked(true);
                        entity.setIsChecked(true);
                        map.put(entity.getJobTypeName(), entity.getId());
                    } else {
                        ToastUitl.showShort(mContext.getResources().getString(R.string.reach_the_limit));
                    }
                }
                mPresenter.getSelectedData(map);
            }
        });
        addAnimation(holder);
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    /**
     * 需要动态的测量listview的高度
     *
     * @param listView
     */
    public void setListViewHeightBasedOnChildren(ListView listView) {

        ListAdapter listAdapter = listView.getAdapter();

        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));

//        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10); // 可删除
        listView.setLayoutParams(params);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        MyViewHolder myViewHolder = new MyViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_jobtype_parent, parent, false));
        return myViewHolder;
    }



    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView mTitle;
        LinearLayout mLinear;
        ImageView statusImg;
        ListView mListView;

        public MyViewHolder(View itemView) {
            super(itemView);
            mTitle = (TextView) itemView.findViewById(R.id.title);
            mLinear = (LinearLayout) itemView.findViewById(R.id.linear);
            statusImg = (ImageView) itemView.findViewById(R.id.iv_jobtype_p);
            mListView = (ListView) itemView.findViewById(R.id.listview);
        }
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    /**
     * header 布局
     *
     * @param position
     * @return
     */
    @Override
    public long getHeaderId(int position) {
        return mData.get(position).getParentId();
    }

    @Override
    public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_header, parent, false);
        return new RecyclerView.ViewHolder(view) {
        };
    }

    @Override
    public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int position) {
        TextView textView = (TextView) holder.itemView.findViewById(R.id.tvHeader);
        for (JobTypeEntity entity : mParentData) {
            if (entity.getId() == mData.get(position).getParentId()) {
                textView.setText(entity.getJobTypeName());
            }
        }
    }

    /**
     * 第三层职位listview adapter
     */
    public class MyAdapter extends BaseAdapter {
        List<JobTypeEntity> childData = new ArrayList<>();

        public MyAdapter(List<JobTypeEntity> child) {
            childData = child;
        }

        @Override
        public int getCount() {
            return childData.size();
        }

        @Override
        public Object getItem(int position) {
            return childData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final JobTypeEntity entity = childData.get(position);
            final ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_jobtype_child, null);
                viewHolder.mTitle = (TextView) convertView.findViewById(R.id.title);
                viewHolder.childLinear = (LinearLayout) convertView.findViewById(R.id.child_linear);
                viewHolder.childChecked = (CheckBox) convertView.findViewById(R.id.title_check);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            for (Map.Entry entry : map.entrySet()) {
                String key = (String) entry.getKey();
                if (entity.getJobTypeName().equals(key)) {
                    entity.setIsChecked(true);
                }
            }
            viewHolder.childChecked.setChecked(entity.getIsChecked());
            viewHolder.mTitle.setText(childData.get(position).getJobTypeName());
            return convertView;
        }

        public class ViewHolder {
            TextView mTitle;
            LinearLayout childLinear;
            CheckBox childChecked;
        }
    }
    public void updateListView(List<JobTypeEntity> mChildDataList) {
        this.mChildData = mChildDataList;
        notifyDataSetChanged();
    }
    /**
     * @param key
     */
    public void notifyData(String key) {
        for (JobTypeEntity entity : mChildData){
            if (key.equals(entity.getJobTypeName())){
                entity.setIsChecked(false);
            }
        }
        notifyDataSetChanged();
    }
    /**
     * 添加动画
     *
     * @param holder
     */
    public void addAnimation(RecyclerView.ViewHolder holder) {
        if (mOpenAnimationEnable) {
            if (holder.getLayoutPosition() > mLastPosition) {
                BaseAnimation animation = null;
                if (mSelectAnimation != null) {
                    animation = mSelectAnimation;
                }
                for (Animator anim : animation.getAnimators(holder.itemView)) {
                    startAnim(anim, holder.getLayoutPosition());
                }
                mLastPosition = holder.getLayoutPosition();
            }
        }
    }

    /**
     * 开始动画
     *
     * @param anim
     * @param index
     */
    protected void startAnim(Animator anim, int index) {
        anim.setDuration(mDuration).start();
        anim.setInterpolator(mInterpolator);
    }

    /**
     * 设置动画
     *
     * @param animation ObjectAnimator
     */
    public void openLoadAnimation(BaseAnimation animation) {
        this.mOpenAnimationEnable = true;
        this.mSelectAnimation = animation;
    }
}
